package com.ias.agdis_r.util;

import android.util.Log;

import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.volley.JSONUtil;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by qibo.yu on 2015/10/23.
 */
public class DnsIpConfigHelper {

    private static final String TABLE_NAME = ParameterModel.T_DNS_CONFIG;

    private DataBaseManager manager;

    private String wifiPrefix, publicPrefix, privatePrefix;

    public DnsIpConfigHelper(DataBaseManager manager) {
        this.manager = manager;

        wifiPrefix = getString("wifiPrefix", "wifi_");
        publicPrefix = getString("publicPrefix", "public_");
        privatePrefix = getString("privatePrefix", "private_");

    }


    public void saveConfig(JSONObject config) {
        Map<String, Object> map = JSONUtil.parseJsontoMap(config);
        List<Map<String, Object>> hosts = (List<Map<String, Object>>) map.get("hosts");

        System.out.println("&&&" + hosts);
        for (Map<String, Object> host : hosts) {
            saveHost(host);
        }

    }

    private void saveHost(Map<String, Object> host) {
        String name = (String) host.get("name");
        String port = ((Double) host.get("port")).intValue() + "";
        String ip = (String) host.get("ip");

        if (name.startsWith(wifiPrefix)) {
            saveHostToTable(ParameterModel.T_WIFI_INFO, name.substring(wifiPrefix.length()), ip, port);
        } else if (name.startsWith(privatePrefix)) {
            saveHostToTable(ParameterModel.T_PRIVATE_INFO, name.substring(privatePrefix.length()), ip, port);
        } else if (name.startsWith(publicPrefix)) {
            saveHostToTable(ParameterModel.T_PUBLIC_INFO, name.substring(publicPrefix.length()), ip, port);
        }

    }

    private void saveHostToTable(String table, String type, String ip, String port) {

        String ipKey = "ip_" + type;
        String portKey = "port_" + type;

        StringBuffer buffer = new StringBuffer("Update table ").append(table);
        buffer.append(" with ").append(ipKey).append(":").append(ip);
        buffer.append(" and ").append(portKey).append(":").append(port).append(".");

        Log.i("C_net_config", buffer.toString());

        manager.insert(table, ipKey, ip);
        manager.insert(table, portKey, port);
    }

    private String getString(String key, String defaultString) {
        String str = manager.getString(TABLE_NAME, key);
        if (null == str || "".equals(str)) {
            return defaultString;
        }
        return str;
    }

}
